<template>
<view class="index">
	<!-- 地图部分 -->
	<view class="map">
		<map id="myMap" style="width: 100%; height: 100%;" :markers="map.markers" :latitude="map.center[1]" :longitude="map.center[0]" 
			@regionchange="regionchange" show-location	@markertap="markertap" @tap="tap" @controltap="controltap" :controls="controls"></map>
	</view>
	
	<cover-image src="/static/indexZhaoshangBtn.png" class="zhaoshangBtn" @tap="callKefu"></cover-image>
	
	<cover-view class="bottom">
		<cover-view style="width: 100%; height: 100%; display: flex; flex-direction: row; justify-content: space-around; align-items: center;">
			<cover-image @tap="toshoplist" style="width: 96upx; height: 82upx; margin-left: 20upx;" src="../../static/local.png"></cover-image>
			<cover-image @tap="scanCode" style="width: 400upx; height: 150upx;" src="../../static/indexSubmit.png"></cover-image>
			<cover-image @tap="toPerson" style="width: 98upx; height: 82upx; margin-right: 20upx;" src="../../static/person.png"></cover-image>
		</cover-view>
	</cover-view>
	
	<cover-image src="/static/came.png" class="cameBtn"></cover-image>
	<cover-image src="/static/indexCenterBtn.png" class="centerBtn" @tap="movelocation"></cover-image>
	<cover-image src="/static/indexFindBtn.png" class="findBtn" @tap="selePosition"></cover-image>
	<cover-image src="/static/indexHelpBtn.png" class="helpBtn" @tap="turnTo( 'help' )"></cover-image>
	
	<cover-view class="bus-detail" v-if="shop.blank" @tap="turnToShop">		
		<cover-view class="topItem">
			<cover-image :src="shop.info.shopPhotUrl || '/static/logo.png'" style="width: 130upx; height: 130upx;"></cover-image>
			<cover-view class="topRight">
				<cover-view class="topRightFlex">
					<cover-view style="font-size: 33upx; color: #122a2a; font-weight: 600;">{{ shop.info.shopName || '无' }}</cover-view>
					<cover-view style="font-size: 18upx; color: #768181;">{{ shop.info.lang || 0 }}</cover-view>
				</cover-view>
				<cover-view style="font-size: 20upx; color: #b4bdbe; width: 100%;">{{ shop.info.shopSite || '无' }}</cover-view>
				<cover-view style="font-size: 24upx; color: #455354; height: 36upx; line-height: 36upx; width: 100%;">营业时间:{{ shop.info.shopHours || '无' }}</cover-view>
			</cover-view>
		</cover-view>
		<cover-view style="display: flex; flex-direction: row; justify-content: flex-start; align-items: center;">
			<cover-view style="font-size: 20upx; color: #455354; margin-left: 22upx;">{{ shop.info.ifBorrow !== 0 ? '不' : '' }}可租借</cover-view>
			<cover-view style="font-size: 20upx; color: #455354; margin-left: 22upx;">{{ shop.info.ifReturn !== 0 ? '不' : '' }}可归还</cover-view>
		</cover-view>
	</cover-view>
	
</view>
</template>


<script>
import { HTTP } from '../../http.js'
let http = new HTTP;
let height = 30;
let padding = 10;
let EARTH_RADIUS = 6378137.0;
export default {
	data() {
		return {
			windowWidth: 320,
			ifShouquan: false,
			scale: 16,
			timeSwitch: 0,
			showAnd: false,
			switch: false,
			controls: [],
			info: {},
			provider: null,
			userInfo:{
				info: { avatar: '/static/user.png' },
				sysinfo: {},
				getInfo: (cb)=>{	
					this.blank.cb=cb;
					this.blank.show=true;
				},
				getToken: (code,info,provider,cb)=>{	
					http.request({
						url: `login/zfb?code=${code}&avatar=${info.avatar}&nickName=${info.nickName||''}&gender=${info.gender}&countryCode=${info.countryCode}&province=${info.province}&city=${info.city}`,
						method: 'post',
						success: (res)=>{
							uni.setStorage({ 
								key: 'user', 
								data: res.dataList, 
								success: ()=>{
									this.userInfo.sysinfo=res.dataList;	
									if(cb) cb();
								} 
							})
						}
					});	
				},
				getUserLocation: ()=>{
					uni.getLocation({ 
						success: (res)=>{
							this.userInfo.getMarkers(res.longitude, res.latitude);
							this.map.center=[ res.longitude, res.latitude ];
							this.map.position=[ res.longitude, res.latitude ];
							setTimeout(()=>{ this.movelocation(); },500);
							// this.map.object.moveToLocation();
						},
						fail: ()=>{
							// setTimeout(()=>{ this.userInfo.getUserLocation(); },500);							
						}
					});
				},
				// 获取初始点的shop
				getMarkers: (longitude, latitude)=>{
					if(this.userInfo.sysinfo.token&&longitude&&latitude){
						http.request({
							url: `ShopManageController/getGraticulesShopList?longitude=${longitude}&latitude=${latitude}`,
							method: 'get',
							success: (res)=>{								
								let arr=res.dataList||[],list=[];
								arr.forEach(v=>{
									if(!this.shop.markerJson[v.shopId]){
										this.shop.markerJson[v.shopId]=JSON.parse(JSON.stringify(v));
									}
									list.push({ id: v.shopId, ...v, iconPath: '/static/icon.png', width: this.windowWidth*0.1, height: this.windowWidth*0.11 });
								});
								this.map.markers=list;
							}
						});
					}
				},
			},
			map: {
				center: [ 116.39742, 39.909, 16 ],
				position: [],
				object: null,
				timer: null,
				markers: [],
				init: ()=>{
					this.map.object=uni.createMapContext('myMap');	
				},
 				getShoplist: (longitude, latitude)=>{
					if(this.userInfo.sysinfo.token&&longitude&&latitude){			
						http.request({
							url: `ShopManageController/getGraticulesShopList?longitude=${longitude}&latitude=${latitude}`,
							method: 'get',
							success: (res)=>{		
								let arr=res.dataList||[],list=[];
								arr.forEach(v=>{
									if(!this.shop.markerJson[v.shopId]){
										this.shop.markerJson[v.shopId]=JSON.parse(JSON.stringify(v));
									}
									list.push({ id: v.shopId, ...v, iconPath: '/static/icon.png', width: this.windowWidth*0.1, height: this.windowWidth*0.11 });	
								});
								this.map.markers=list;
							}
						});
					}	
				}
			},
			shop: {
				blank: false,
				info: {},
				markerJson: {},
				getInfo: (id)=>{
					this.map.markers.forEach(ele=>{
						if(ele.id==id){  
							let lang=this.getFlatternDistance( this.map.position[1], this.map.position[0], ele.latitude, ele.longitude );
							this.shop.markerJson[id].lang=lang;
							ele.height=this.windowWidth*0.143; 
							ele.width=this.windowWidth*0.13; 
							ele.callout={ content: lang, padding: 6, borderRadius: 5, bgColor: '#000', color: '#fff' }; 
						}else{ ele.height=this.windowWidth*0.11; ele.width=this.windowWidth*0.1; }
					})
					if(this.shop.markerJson[id].shopName){
						this.shop.info=this.shop.markerJson[id];		
						this.shop.blank=true;				
					}else{
						http.request({
							url: `ShopManageController/getShopManage?shopId=${id}`,
							method: 'get',
							success: (res)=>{		
								let json=res.dataList||{};
								this.shop.markerJson[id]=json;
								this.shop.info=JSON.parse(JSON.stringify(json));
								this.shop.blank=true;
							}
						});						
					}
				},
				close(){
					this.blank=false;
					this.info={};
				},
				shopClick(){
					this.turnTo(`shop?id=${ this.shop.info.shopId }`)
				}
			}
		}
	},
	methods: {
		toshoplist() {
			this.shifouzhuce(()=>this.turnTo('shoplist'),()=>this.turnTo('getmes?cb=shoplist'));
		},
		// 跳到个人中心
		toPerson() {
			this.shifouzhuce(()=>this.turnTo('person'),()=>this.turnTo('getmes?cb=toPerson'));								
		},
		// 扫码充电
		scanCode() {			
			this.shifouzhuce(
				()=>{
					this.getRight(()=>{
						uni.scanCode({
							onlyFromCamera: true,
							success: (res)=>{
								let str=res.result||'';
								this.jiexichongdian(str);
							}
						});
					});					
				},
				()=>this.turnTo('getmes?cb=scanCode')
			);
		},
		jiexichongdian(str,init) {
			let strArr;
			if(str.indexOf('https://qr.dianxiaotong.net?=')==0){				
				strArr=str.split('https://qr.dianxiaotong.net?=')[1];
			}else if(str.indexOf('https://qr.dianxiaotong.net?id=')==0){			
				strArr=str.split('https://qr.dianxiaotong.net?id=')[1];
			}	
			if(strArr){ 
				this.turnTo('device?id='+strArr);
			}else{
				if(!init) uni.showModal({ content: "请扫描正确的二维码，该二维码非本系统设备！", showCancel: false }); 
			}				
		},
		getRight(cb){	
			uni.showLoading({ title: '加载中', mask: true });
			http.request({
				url: `orderFormController/notPayOrder?userId=${this.userInfo.sysinfo.userId}`,
				method: 'get',
				success: (res)=>{
					uni.hideLoading();
					if(res.dataList&&res.dataList.orderId){
						let orderId=res.dataList.orderId;
						uni.showModal({
							title: '提示',
							content: '检测到尚有订单未完成，是否立即查看该订单详情！',
							success: (res)=>{
								if(res.confirm){
									this.turnTo('dingdanxiangqing?id='+orderId);
								}
							}
						});
					}else{
						if(cb) cb();
					}
				},
				fail: ()=>{
					uni.hideLoading();					
				}
			});	
		},
		regionchange(e) {
			if(e.type === 'end') {
				this.map.object.getCenterLocation({ success: (res)=>{
					if(this.userInfo.sysinfo.token) this.map.getShoplist(res.longitude, res.latitude);
					this.map.center=[ res.longitude, res.latitude ];
				}});		
			}					
		},
		tap(e){ this.shop.close(); },
		markertap(e){ this.shop.getInfo(e.markerId) },
		getRad(d){ let PI = Math.PI; return d*PI/180.0; },
		getFlatternDistance(lat1,lng1,lat2,lng2){
			var radLat1 = this.getRad(lat1);
			var radLat2 = this.getRad(lat2);
			var a = radLat1 - radLat2;
			var b = this.getRad(lng1) - this.getRad(lng2);
			var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
			s = s*EARTH_RADIUS;
			s = Math.round(s*10000)/10000.0;
			s = Math.floor(s);
			if(s>1000){
				s=Math.round(s/1000*100)/100+'km';
			}else{
				s=s+'m';
			}
			return s
		},
		selePosition(){
			uni.chooseLocation({
				success: (res)=>{
					this.map.center=[ res.longitude, res.latitude ];
					// this.map.object.moveToLocation();
				}
			});
		},
		shifouzhuce(cb,err){	
			console.log('shifouzhuce', this.ifShouquan)
			if(this.ifShouquan){  
				cb();
			}else{				
				this.ifShouquan=true;
				cb();
			}	
		},	
		clickMap(e) {
			if(e.controlId==1) { this.scanCode(); }
		},
		movelocation() { 
			if(this.map.object){ this.map.object.moveToLocation(); }
			else setTimeout(()=>{ this.movelocation(); },300);
		},
		turnTo(name) { 
			if(this.switch) return ;
			this.switch=true
			uni.navigateTo({ url: name, success: ()=>{ this.switch=false }, fail: ()=>{ this.switch=false } }); 
		},
		turnToShop() {
			this.turnTo('shop?id='+this.shop.info.shopId);
		},
		controltap(e) {
			if(e.controlId == 'indexFindBtn') this.selePosition();
			else if(e.controlId == 'indexCenterBtn') this.movelocation();
			else if(e.controlId == 'indexHelpBtn') this.turnTo('help');
			else if(e.controlId == 'indexZhaoshangBtn') this.callKefu();
		},
		callKefu(){ uni.makePhoneCall({ phoneNumber: '400-003-9881' }); }
	},
	onLoad(e) {
		uni.getSystemInfo({ 
			success: (res) => {
				let bili = res.windowWidth / 750;
				this.windowWidth = res.windowWidth;
				if( res.platform == "android" ){
					this.controls=[];
				}else{
					this.controls=[
						{
							id: 'indexZhaoshangBtn',
							iconPath: '/static/indexZhaoshangBtn.png',
							clickable: true,
							position: { width: Math.floor(606 * bili), height: Math.floor(170 * bili), left: Math.floor(73 * bili), top: Math.floor(40 * bili) }
						},
						{
							id: 'indexFindBtn',
							iconPath: '/static/indexFindBtn.png',
							clickable: true,
							position: { width: Math.floor(112 * bili), height: Math.floor(112 * bili), left: Math.floor(27 * bili), top: Math.floor(res.windowHeight - ( 398 + 112 ) * bili) }
						},
						{
							id: 'indexCenterBtn',
							iconPath: '/static/indexCenterBtn.png',
							clickable: true,
							position: { width: Math.floor(112 * bili), height: Math.floor(112 * bili), left: Math.floor(27 * bili), top: Math.floor(res.windowHeight - ( 264 + 112 ) * bili) }
						},
						{
							id: 'indexHelpBtn',
							iconPath: '/static/indexHelpBtn.png',
							clickable: true,
							position: { width: Math.floor(112 * bili), height: Math.floor(112 * bili), left: Math.floor(res.windowWidth - (27 + 112) * bili), top: Math.floor(res.windowHeight - ( 264 + 112 ) * bili) }
						}			
					];
				}				
			}
		})
		this.map.init();
		this.userInfo.getUserLocation();	
		// console.log(e,'页面层检测');		
		this.shifouzhuce(()=>{
			if(my.getOpenUserInfo){
				my.getOpenUserInfo({
					success: (res)=>{
						console.log(res, 'getOpenUserInfo', '获取用户信息成功');					
						let json=JSON.parse(res.response);
						console.log(json);
						let info=json.response;
						this.userInfo.info=info;
						this.userInfo.info.nickName = this.userInfo.info.nickName || '支付宝用户';
						uni.login({ success: (res)=>{
							this.userInfo.getToken(res.code,this.userInfo.info,this.provider,
								()=>{
									if(e.cb&&e.cb=='toPerson'){ this.toPerson(); }
									if(e.cb&&e.cb=='scanCode'){ this.scanCode(); }
									if(e.cb&&e.cb=='shoplist'){ this.toshoplist(); }
									let qrCode = this.$store.qrcode;
									if(qrCode){ this.getRight(()=>this.jiexichongdian(qrCode,true)); }
								}
							); 							
						}});
					},
					fail: () => {
						this.userInfo.info={ nickName: '支付宝用户' };
						uni.login({ success: (res)=>{
							this.userInfo.getToken(res.code,this.userInfo.info,this.provider,
								()=>{
									if(e.cb&&e.cb=='toPerson'){ this.toPerson(); }
									if(e.cb&&e.cb=='scanCode'){ this.scanCode(); }
									if(e.cb&&e.cb=='shoplist'){ this.toshoplist(); }
									let qrCode = this.$store.qrcode;
									if(qrCode){ this.getRight(()=>this.jiexichongdian(qrCode,true)); }
								}
							); 							
						}});
					}
				});					
			}else{	
				my.alert({ title: '提示', content: '当前支付宝版本过低，无法使用此功能，请升级最新版本支付宝' });
			}
		}); 
	}
}
</script>

<style>
.index {
	text-align: center;
	height: 100vh;
	position: relative;
}

.index .map {
	width: 100%;
	height: 100%;
	position: absolute;
	z-index: 5;
	box-sizing: border-box;
	bottom: 0;
	left: 0;
	padding-bottom: 150upx;
}

.index .zhaoshangBtn {
	width: 606upx;
	height: 170upx;
	border-radius: 10upx;
	z-index: 10;
	position: absolute;
	top: 40upx;
	left: 72upx;
}

.index .bottom {
	width: 100%;
	height: 180upx;
	background: #FFF;
	z-index: 10;
	position: absolute;
	bottom: 0;
	left: 0;	
	box-shadow: 0upx -3upx 10upx 0upx rgba(241, 243, 245, 0.54);
	border-radius: 30upx 30upx 0upx 0upx;
}

.index .centerBtn {
	width: 112upx;
	height: 112upx;
	z-index: 10;
	position: absolute;
	bottom: 264upx;
	left: 27upx;	
	border-radius: 50%;
}

.index .findBtn {
	width: 112upx;
	height: 112upx;
	z-index: 10;
	position: absolute;
	bottom: 398upx;
	left: 27upx;	
	border-radius: 50%;
}

.index .helpBtn {
	width: 112upx;
	height: 112upx;
	z-index: 10;
	position: absolute;
	bottom: 264upx;
	right: 27upx;	
	border-radius: 50%;
}

.index .cameBtn {
	width: 40upx;
	height: 70upx;
	z-index: 50;
	position: absolute;
	left: 50%;
	top: 50%;
	margin-left: -20upx;
	margin-top: -130upx;
}

.index .bus-detail {
	position: absolute;
	bottom: 190upx;
	left: 40upx;
	width: 670upx; 
	z-index: 60;
	box-sizing: border-box; 
	padding: 30upx 40upx; 
	border: solid 1upx #f2f2f2; 
	background-color: #fff;
	border-radius: 10upx; 
	text-align: left;
	box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.1);
}
.bus-detail .topItem {
	width: 100%;
	height: 180upx;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: flex-start;
}
.bus-detail .topRight {
	width: 440upx;
	height: 130upx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: center;	
}
.bus-detail .topRightFlex {
	width: 100%;
	height: 35upx;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;	
}
.index .bus-detail .title {
	padding: 20upx;
	border-bottom: 1px dashed #eee;
}
.index .bus-detail .right {
	display: inline-block;
	margin-left: 20upx;
}
.index .bus-detail .title cover-image {
	display: inline-block;
	width: 150upx;
	height: 150upx;
}
.index .bus-detail .right .name {
	line-height: 60upx;
	font-size: 36upx;
	color: #333;
}
.bus-detail .right .address {
	line-height: 50upx;
	font-size: 26upx;
	color: #bbb;
}
.bus-detail .right .time {
	line-height: 40upx;
	font-size: 26upx;
	color: #777;
}
.bus-detail .status {
	padding: 20upx;
	color: #666;
	font-size: 26upx;
}
</style>
